package com.xyzq.cgate.admin.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.xyzq.cgate.admin.mapper.PluginMapper;
import com.xyzq.cgate.admin.service.PluginService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xyzq.cgate.common.constant.ZkPathConstants;
import com.xyzq.cgate.common.entity.Plugin;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.management.PlatformLoggingMXBean;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenchen
 * @since 2019-06-06
 */
@Service
public class PluginServiceImpl extends ServiceImpl<PluginMapper, Plugin> implements PluginService {

    @Autowired
    private ZkClient zkClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertDbAndZk(Plugin plugin) {
        this.insert(plugin);
        insertPluginDataToZk(plugin);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDbAndZk(EntityWrapper<Plugin> entityWrapper, Plugin plugin) {
        this.delete(entityWrapper);
        removeAllZkDataByParentPath(ZkPathConstants.buildPluginZkPath(plugin.getName()));
        removeAllZkDataByParentPath(ZkPathConstants.buildRuleZkPath(plugin.getName()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDbAndZk(Plugin plugin, EntityWrapper<Plugin> entityWrapper) {
        this.update(plugin, entityWrapper);
        insertPluginDataToZk(plugin);
    }

    @Override
    public void insertPluginDataToZk(Plugin plugin) {
        String pluginZkPath = ZkPathConstants.buildPluginZkPath(plugin.getName());
        if(!zkClient.exists(pluginZkPath)) {
            zkClient.createPersistent(pluginZkPath, true);
        }
        zkClient.writeData(pluginZkPath, plugin);
    }

    @Override
    public void removeAllZkDataByParentPath(String parentPath) {
        if (zkClient.exists(parentPath)) {
            zkClient.deleteRecursive(parentPath);
        }
    }
}
